<template>
  <!-- mescroll-uni本质是scroll-view,支持局部区域滚动,可使用flex布局灵活的嵌在某个view中, 而mescroll-body只能靠fixed定位其他元素变相实现'局部滚动' -->
  <view class="page-warp">
    <scroll-view
      class="top-warp"
      :scroll-x="true"
      :scroll-with-animation="true"
    >
      <view
        style="display: inline-block"
        @click="tagCLick(item, index)"
        :class="active == index ? 'active' : 'tagItem'"
        v-for="(item, index) in list"
        :key="index"
      >
        {{ item.name }}
      </view>
    </scroll-view>

    <view class="center-warp">
      <!-- 左边 -->
      <scroll-view class="left-warp" :scroll-y="true">
        <view
          class="tab"
          :class="{ active: i == tabIndex }"
          v-for="(item, i) in tabs"
          :key="i"
          @click="tabChange(item, i)"
        >
          <u-avatar size="28" :src="item.icon"></u-avatar>
          <text>{{ item.name }}</text>
        </view>
      </scroll-view>

      <view class="right-warp">
        <scroll-view
          class="scrool"
          :scroll-x="true"
          :scroll-with-animation="true"
        >
          <view class="three">
            <view
              @click="threeClik(item, index)"
              :class="
                threeActive == index ? 'threeItem threeActive' : 'threeItem'
              "
              v-for="(item, index) in threeList"
              :key="index"
            >
              {{ item.name }}
            </view>
          </view>
        </scroll-view>

        <!--右边 :fixed="false", 高度跟随父元素 (不在组件上定义class,避免部分小程序平台编译丢失, 如支付宝,钉钉小程序) -->
        <mescroll-uni
          :fixed="false"
          ref="mescrollRef"
          @init="mescrollInit"
          @down="downCallback"
          @up="upCallback"
          :down="downOption"
          :up="upOption"
        >
          <view
            class="goodItem"
            v-for="(item, index) in goods"
            :key="index"
            @click.stop="goDetail(item)"
          >
            <image
              :src="
                item.pic
                  ? (item.pic.startsWith('https')
                    ? item.pic
                    : 'https://saas.hzjhckj.com/api' + item.pic)
                  : 'https://building-d.oss-cn-hangzhou.aliyuncs.com/img/img.jpg'
              "
              mode=""
            ></image>
            <view class="goodRight">
              <view class="title">
                {{ item.name }}
              </view>
              <view v-if="item.brandName">{{ item.brandName }}</view>
              <view class="top">
                <view class="price">
                  ￥{{ item.minPrice == "null" ? "-" : item.minPrice }}
                </view>
                <view class="btn">
                  <u-button
                    @click.native.stop="addCar(item)"
                    color="#FF0000"
                    size="mini"
                    icon="plus"
                  ></u-button>
                </view>
              </view>
            </view>
          </view>
        </mescroll-uni>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getCategoryTree,
  productSearchByCategoryId,
  mallBrandPage,
} from "@/api/cate.js";
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins";
import { addCar } from "@/api/goods";

export default {
  mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
  data() {
    return {
      downOption: {
        auto: false,
        textNoMore: "我是有底线的 >_<",
      },
      upOption: {
        auto: false,
        textNoMore: "我是有底线的 >_<",
      },
      active: 0,
      list: [],
      goods: [], // 数据列表
      tabs: [],
      tabIndex: 0, // tab下标
      threeList: [],
      threeActive: 0,
      categoryId: "",
      brandId: "",
      isDetailBack: "",
    };
  },
  async onShow() {
    // 获取页面栈
    this.isDetailBack = uni.getStorageSync("detail1") === "1" ? true : false;

    this.active = 0;
    this.list = [];
    this.threeList = [];
    this.categoryId = "";
    this.brandId = "";
    this.threeActive = 0;
    this.getCategoryTree();
  },
  methods: {
    // 品牌
    async getBrand() {
      let brands = [];
      try {
        const x = await mallBrandPage(this.categoryId, {
          page: 1,
          size: 100,
        });
        brands = x.records || [];
      } catch (error) {}
      brands.unshift({
        name: "全部",
        id: "",
      });
      this.threeList = brands;
    },
    goDetail(item) {
      uni.setStorageSync("detail", {
        active: this.active,
        tabIndex: this.tabIndex,
        threeActive: this.threeActive,
      });
      this.$navTo("pages/goods/detail", {
        // goodsId: item.skuId,
        productId: item.productId,
        name: item.name
      });
    },
    async addCar(item) {
      const res = await addCar({
        skuId: item.id,
        productId: item.productId,
        num: 1,
      });
      uni.showToast({
        title: "加入购物车成功",
      });
    },
    async getCategoryTree() {
      uni.showLoading();
      try {
        const res = await getCategoryTree({
          navStatus: 1,
          showStatus: 1,
        });
        this.list = res; // 一级目录
        this.goods = [];

        const navName = uni.getStorageSync("navName"); // 首页->分类
        if (navName) {
          for (let i = 0; i < this.list.length; i++) {
            if (this.list[i].id == navName) {
              this.tabs = this.list[i].children; // 二级
              this.active = i
              break
            }
          }
          this.tabChange(this.tabs[0], 0);
          this.mescroll.resetUpScroll(); // 重置列表数据
          uni.removeStorageSync("navName");
        } else if (this.isDetailBack) {
          const detail = uni.getStorageSync("detail"); // 详情页->分类
          let { threeActive, active, tabIndex } = detail;
          this.active = active;
          this.tabs = res[active].children;
          this.categoryId = this.tabs[tabIndex].id;
          this.tabIndex = tabIndex;
          await this.getBrand();
          this.threeActive = threeActive;
          this.brandId = this.threeList[threeActive].id;
          this.goods = [];
          this.mescroll.resetUpScroll();
          uni.removeStorageSync("detail");
          uni.removeStorageSync("detail1");
        } else {
          this.tabs = res[0].children;
          this.tabChange(this.tabs[0], 0);
          this.mescroll.resetUpScroll(); // 重置列表数据
        }
      } catch (error) {}
      uni.hideLoading();
    },
    // 子集
    upCallback(page) {
      //联网加载数据
      // let keyword = this.tabs[this.tabIndex]
      productSearchByCategoryId({
        current: page.num,
        size: page.size,
        categoryId: this.categoryId,
        brandId: this.brandId,
      })
        .then((res) => {
          this.goods = this.goods.concat(res.records); //追加新数据
          this.mescroll.endBySize(res.records.length, res.total);
          // //联网成功的回调,隐藏下拉刷新和上拉加载的状态;
          // this.mescroll.endSuccess(curPageData.length);
          // //设置列表数据
          // if (page.num == 1) this.goods = []; //如果是第一页需手动制空列表
          // this.goods = this.goods.concat(curPageData); //追加新数据
        })
        .catch(() => {
          //联网失败, 结束加载
          this.mescroll.endErr();
        });
    },
    // 一级
    tagCLick(item, index) {
      this.active = index;
      this.categoryId = "";
      this.brandId = "";
      this.tabs = item.children || [];
      if (item.children) {
        this.tabChange(this.tabs[0], 0);
        this.goods = []; // 先置空列表,显示加载进度条
        this.mescroll.resetUpScroll(); // 重置列表数据
      }
    },
    // 分类
    tabChange(item, i) {
      this.brandId = "";
      this.categoryId = item.id;
      this.getBrand();
      this.threeActive = 0;
      if (this.tabIndex != i) {
        this.tabIndex = i;
        this.goods = []; // 先置空列表,显示加载进度条
        this.mescroll.resetUpScroll(); // 重置列表数据
      }
    },
    threeClik(item, index) {
      this.brandId = item.id;
      console.log("threeClik", item);
      this.threeActive = index;
      this.goods = []; // 先置空列表,显示加载进度条
      this.mescroll.resetUpScroll(); // 重置列表数据
    },
  },
};
</script>

<style>
page {
  background: #f5f5f5;
}
</style>
<style lang="scss">
/*根元素需要有固定的高度*/
page {
  height: 100%;
  // 支付宝小程序,钉钉小程序需添加绝对定位,否则height:100%失效: https://opendocs.alipay.com/mini/framework/acss#%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98
  /* #ifdef MP-ALIPAY || MP-DINGTALK*/
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  /* #endif */

  /*需给父元素设置height:100%*/
  .page-warp {
    height: 100%;
    display: flex;
    flex-direction: column;

    /* 顶部区域 */
    .top-warp {
      // display: flex;
      background-color: #fff;
      font-size: 28rpx;
      padding: 20rpx;
      white-space: nowrap;
      border-bottom: 1rpx solid rgba(207, 224, 218, 0.3);
      overflow: hidden;

      .tagItem {
        position: relative;
        padding: 0 30rpx;
        color: #999;

        &:before {
          position: absolute;
          content: "";
          display: inline-block;
          width: 40rpx;
          background-color: transparent;
          height: 7rpx;
          bottom: -10rpx;
          left: 50%;
          transform: translateX(-50%);
          border-radius: 2rpx;
        }
      }

      .active {
        position: relative;
        color: #333;
        font-weight: 700;
        padding: 0 30rpx;

        &:before {
          position: absolute;
          content: "";
          display: inline-block;
          width: 40rpx;
          background-color: #333;
          height: 7rpx;
          bottom: -10rpx;
          left: 50%;
          transform: translateX(-50%);
          border-radius: 2rpx;
        }
      }
    }

    /* 中间 */
    .center-warp {
      flex: 1;
      min-width: 0;
      min-height: 0;
      /* 需给flex:1的元素加上最小高,否则内容超过会溢出容器 (如:小程序Android真机) */
      // border: 4px solid red;
      display: flex;

      // 左边
      .left-warp {
        width: 180rpx;
        height: 100%;

        .tab {
          display: flex;
          align-items: center;
          justify-content: space-around;
          font-size: 28rpx;
          padding: 30rpx 20rpx;
          background-color: #fff;
          color: #999;
          border-left: 4rpx solid transparent;

          &.active {
            color: #333;
            font-weight: 700;
            background-color: #fff;
            border-left: 4rpx solid #999;
          }
        }
      }

      // 右边
      .right-warp {
        flex: 1;
        min-width: 0;
        background-color: #fff;

        .scrool {
          overflow: hidden;
          // width: 400rpx;
          white-space: nowrap;
        }

        .threeItem {
          display: inline-block;
          padding: 10rpx 25rpx;
          border: 1rpx solid #999;
          margin-left: 20rpx;
          border-radius: 25rpx;
        }

        .threeActive {
          background-color: #ff0000;
          border: 1rpx solid transparent;
          color: #fff;
        }

        .three {
          display: flex;
          height: 90rpx;
          align-items: center;
          font-size: 24rpx;
          border-bottom: 1rpx solid rgba(207, 224, 218, 0.3);
        }
      }
    }

    /* 底部区域 */
    // .bottom-warp {
    // 	padding: 20rpx;
    // 	text-align: center;
    // 	background-color: #FF6990;
    // }
  }
}

.goodItem {
  display: flex;
  padding: 15rpx 10rpx;
  font-size: 30rpx;
  border-bottom: 1rpx solid rgba(207, 224, 218, 0.5);

  image {
    width: 200rpx;
    height: 200rpx;
  }

  .goodRight {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 20rpx 10rpx;
    width: calc(100% - 200rpx);

    .top {
      display: flex;
      justify-content: space-between;
    }

    .price {
      color: #ff0000;
    }

    ::v-deep .u-icon__icon {
      color: #fff !important;
      font-weight: 700;
    }
  }
}
</style>
